package org.example.maven.controller;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.transaction.Transactional;
import org.example.maven.annotation.ReadOnlyMode;
import org.example.maven.mapper.provenanceSourceMapper;
import org.example.maven.pojo.ProvenanceSource;
import org.example.maven.pojo.Result;
import org.example.maven.pojo.list.ListTableCollection;
import org.example.maven.pojo.list.ListTableCollectionAddDetail;
import org.example.maven.pojo.list.ListTableCollectionDetail;
import org.example.maven.pojo.operation.OperateList;
import org.example.maven.pojo.operation.loginLog.LoginLogList;
import org.example.maven.pojo.user.list.UserListTable;
import org.example.maven.service.ExcelImportService;
import org.example.maven.service.Impl.collectionServiceImpl;
import org.example.maven.service.Impl.provenanceSourceServiceImpl;
import org.example.maven.service.LoginLogService;
import org.example.maven.service.OperateService;
import org.example.maven.service.UserService;
import org.example.maven.utils.SearchIpUtils;
import org.example.maven.utils.excel.ExcelExportUtil;
import org.example.maven.utils.excel.ExcelImportResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.example.maven.mapper.collectionMapper;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@CrossOrigin
public class utilController {
    @Autowired
    private ExcelImportService importService;
    @Autowired
    private collectionServiceImpl collectionService;
    @Autowired
    private provenanceSourceServiceImpl provenanceSourceService;
    @Autowired
    private UserService userService;
    @Autowired
    private OperateService operateService;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private collectionMapper collectionMapper;
    @Autowired
    private provenanceSourceMapper provenanceMapper;
    @GetMapping("/getIpAddress")
    @PreAuthorize("permitAll()")
    //获取用户的IP地址
    public Result getUserLoginAddress(){
        SearchIpUtils.getUserAddress("121.40.32.236");
        return Result.success(SearchIpUtils.getUserAddress("121.40.32.236"));
    }

    @PostMapping("/uploadCollectionFile")
    @PreAuthorize("hasAnyAuthority('collection:all')")
    //进行根据excel表格添加藏品
    @ReadOnlyMode
    public Result uploadCollectionFile(@RequestParam("file")MultipartFile file){
        try {
            ExcelImportResult<ListTableCollectionAddDetail> result = importService.importExcel(
                    file,
                    collectionService,
                    500,
                    list->collectionMapper.addCollectionList(list)
            );
            // 2. 获取插入的藏品ID列表（假设每个藏品对应一个来源）
            List<Integer> collectionIds = result.getSuccessData().stream()
                    .map(ListTableCollectionAddDetail::getId)
                    .toList();
            ExcelImportResult<ProvenanceSource> result1=importService.importExcel(
                    file,
                    (row, rowNum) -> {
                        ProvenanceSource source = provenanceSourceService.parse(row, rowNum);
                        // 按行顺序绑定藏品ID（假设行号对应）
                        source.setCollectionId(collectionIds.get(rowNum - 1)); // 跳过标题行
                        return source;
                    },
                    500,
                    list->provenanceMapper.addProvenanceSourceList(list)
            );
            return Result.success("导入成功",result1.getSuccessData());
        } catch (IOException e) {
            return Result.error("文件处理失败");
        }
    }
    @GetMapping("/museum/{type}")
    @PreAuthorize("hasAnyRole('admin')") // 根据实际权限配置
    public void ExcelExport(@PathVariable String type, HttpServletResponse response) throws IOException {
        switch (type.toLowerCase()) {
            case "user":
                List<UserListTable> users = userService.getAllUser();
                ExcelExportUtil.export(response, users, UserListTable.class, "用户列表");
                break;
            case "collection":
                System.out.println("下载collection");
                List<ListTableCollection> collections = collectionService.getAllCollection();
                ExcelExportUtil.export(response, collections, ListTableCollection.class, "藏品列表");
                break;
            case "operate":
                List<OperateList> operateLists=operateService.getAllOperate();
                ExcelExportUtil.export(response, operateLists, OperateList.class, "操作日志列表");
                break;
            case "logging":
                List<LoginLogList> loginLogLists=loginLogService.getAllLogging();
                ExcelExportUtil.export(response, loginLogLists, LoginLogList.class, "操作日志列表");
                break;
            default:
                response.sendError(HttpStatus.BAD_REQUEST.value(), "不支持的导出类型");
        }
    }
}
